package com.example.gulimall.product.service.impl;

import com.example.common.constant.ProductConstant;
import com.example.common.to.SkuHasStockVo;
import com.example.common.to.SkuReductionTo;
import com.example.common.to.SpuBoundTo;
import com.example.common.to.es.SkuEsModel;
import com.example.common.utils.R;
import com.example.gulimall.product.entity.*;
import com.example.gulimall.product.feign.CouponFeignService;
import com.example.gulimall.product.feign.SearchFeignService;
import com.example.gulimall.product.feign.WareFeignService;
import com.example.gulimall.product.service.*;
import com.example.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.TypeReference;

@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService attrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;

    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuInfo) {
        //1 保存spu基本信息：pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseInfo(infoEntity);
        // 2 保存spu的描述图片 pms_spu_info_desc
        List<String> decript = spuInfo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(infoEntity.getId());
        //String.join将数组中的元素以逗号分隔开
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        //3 保存spu 图片集 pms_spu_images
        spuImagesService.saveImages(infoEntity.getId(), spuInfo.getImages());
        //4 保存spu 规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();

        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.savaProductAttr(collect);
        //5保存spu的积分信息 gulimall_sms->sms_spu_bounds(夸库保存)
        //保存spu的积分信息 gulimall_sms->sms_bounds
        Bounds bounds = spuInfo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
      R cR= couponFeignService.saveSpuBouds(spuBoundTo);
        if(cR.getCode()!=0){
            log.error("远程保存spu积分信息失败");
        }
        //6 保存当前spu对应所有sku信息
        List<Skus> skus = spuInfo.getSkus();
        if (skus != null && skus.size() > 0) {

            for (Skus item : skus) {
                String defaultimg = "";
                for (Images images : item.getImages()) {
                    if (images.getDefaultImg() == 1) {
                        defaultimg = images.getImgUrl();
                    }
                }
                //sku 基本信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultimg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                // sku 图片集保存
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
//                         if (img.getDefaultImg() == 1) {
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());

                    //}
                    return skuImagesEntity;
                }).filter(entity->{
                    //将空地址过滤掉，返回true需要，返回false过滤掉，
                    return StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //6.2   sku图片信息 pms_sku_images
                //TODO 没有图片，路径的无需保存，要过滤
                skuImagesService.saveBatch(imagesEntities);

                //6.3   sku销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //6.4   sku的优惠，满减信息：gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo=new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount()>0||skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){
                    R r= couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode()!=0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            }

        }


        //6.1   sku基本信息 pms_sku_info



    }

    @Override
    public void saveBaseInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

         if (params.containsKey("key")){
            String key=params.get("key").toString();
             if (!StringUtils.isEmpty("key")){
                 wrapper.and(w->{
                     w.eq("id",key).or().like("spu_name",key);
                 });
             }
          }

        if (params.containsKey("status")){
            String status=params.get("status").toString();
            if (!StringUtils.isEmpty(status)){
                wrapper.eq("publish_status",status);
            }
        }

        if (params.containsKey("brandId")){
            String brandId=params.get("brandId").toString();
            if (!StringUtils.isEmpty(brandId)){
                wrapper.eq("brand_id",brandId);
            }
        }
        if (params.containsKey("catelogId")){
            String catelogId=params.get("catelogId").toString();
            if (!StringUtils.isEmpty(catelogId)){
                wrapper.eq("catalog_id",catelogId);
            }
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void spuUp(Long spuId) {

         //查询当前spuid对应的所有sku信息，品牌名字
        List<SkuInfoEntity> skuInfos = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        //第一步发送远程调用的参数
        List<Long> skuIdList = skuInfos.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        // TODO 4 查询当前sku的所有可以用来被检索的规格属性
        List<ProductAttrValueEntity> spuAttrs = attrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = spuAttrs.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

       List<Long> searchAttrIds= attrService.selectSearchAttrs(attrIds);

        Set<Long> idSet=new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> attrsList = spuAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());
        Map<Long, Boolean> stockMap=null;
        try {
            // TODO 1 发送远程调用，库存系统是否有库存
            //这里不知道为啥视频时getHasStock但是我这里变成了HasStock
            R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
//           stockMap = skuHasStock.getData().stream().
//                    collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.()));
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = skuHasStock.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.isHasStock()));
            //用来判断当前sku是否有库存
        }catch (Exception ex){
            log.error("库存服务查询异常：原因{}",ex);
        }

        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skuInfos.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            // 设置库存信息，封装成map避免了循环查库 ,
            if (finalStockMap ==null){
                esModel.setHasStock(true);
            }else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }


            // TODO 2 热度评分 0
            esModel.setHotScore(0L);
            // TODO 3 查询品牌和分类的名字信息 这里品牌id和分类id已经映射上去了因此不用再写
            BrandEntity brand = brandService.getById(sku.getBrandId());
            esModel.setBrandImg(brand.getLogo());
            esModel.setBrandName(brand.getName());
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogName(category.getName());
            //第四步的查询结果
            esModel.setAttrs(attrsList);

            return esModel;
        }).collect(Collectors.toList());

        // 最后将数据封装成SkuEsModel
        //  TODO 5 将数据发送给es进行保存 gulimall-search
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode()==0){
            //远程调用成功 修改sku上架状态
            baseMapper.updateStatus(spuId, ProductConstant.StatusEnum.UP_SPU.getCode());
        }else {
            //远程调用失败
            //TODO 7 重复调用？接口幂等性，重试机制
        }

    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return  spuInfoEntity;
    }


}